package com.rw.coco.handler.message.reply.handler.command;

import com.rw.coco.api.data.PersistenceMapper;
import com.rw.coco.api.data.model.CharacterModel;
import com.rw.coco.api.reply.mapper.DiceReply;
import com.rw.coco.handler.message.event.CocoMessageEvent;
import com.rw.coco.handler.message.reply.ReplyHandler;
import com.rw.coco.handler.message.reply.handler.command.assistant.CommandMatcher;
import com.rw.coco.service.CharacterService;
import com.rw.coco.util.config.CocoCommandConfig;
import com.rw.coco.util.config.CocoConfig;
import com.rw.coco.util.config.CocoOption;
import com.rw.tool.util.string.StringUtil;

/**
 * 更改昵称
 * .nn
 */
public class NNHandler implements ReplyHandler {
    private static final String CLR = "clear";

    private final CommandMatcher matcher;

    public final boolean funcSwitch;

    public NNHandler(CocoConfig cocoConfig) {
        CocoCommandConfig cocoCommandConfig = cocoConfig.getCocoCommandConfig();
        CocoOption cocoOption = cocoConfig.getCocoOption();

        String command = cocoCommandConfig.commandProp.get(CocoCommandConfig.NN);
        this.matcher = CommandMatcher.of(command);
        this.funcSwitch = cocoOption.optionProp.getBoolean(CocoOption.COCO_NN);
    }

    @Override
    public boolean trigger(CocoMessageEvent cocoMessageEvent) {
        String message = cocoMessageEvent.getMessage();
        return funcSwitch && matcher.isMatch(message);
    }

    @Override
    public void handler(CocoMessageEvent cocoMessageEvent) {
        // 去掉nn前缀
        String nick = matcher.subTrim(cocoMessageEvent.getMessage());
        DiceReply diceReply = cocoMessageEvent.getReplyApi().getDiceReply();
        PersistenceMapper mapper = cocoMessageEvent.getDataApi().getPersistenceMapper();
        CharacterService service = new CharacterService(mapper);

        if (StringUtil.isBlank(nick)) {
            // 没有指定昵称，指令错误
            cocoMessageEvent.sendBack(diceReply.nnNotFound(cocoMessageEvent));
        } else if (CLR.equalsIgnoreCase(nick)) {
            // 清除昵称
            CharacterModel characterModel = service.getOrDefault(cocoMessageEvent.getAccountModel());
            mapper.getCharacterMapper().setNick(characterModel.getCharacterId(), StringUtil.EMPTY);
            cocoMessageEvent.sendBack(diceReply.nnClear(cocoMessageEvent));
        } else {
            // 设置昵称
            CharacterModel characterModel = service.getOrDefault(cocoMessageEvent.getAccountModel());
            mapper.getCharacterMapper().setNick(characterModel.getCharacterId(), nick);
            cocoMessageEvent.sendBack(diceReply.nn(cocoMessageEvent, nick));
        }
    }

    @Override
    public int priority() {
        return matcher.priority();
    }
}